/**
 * Created by baiguiren on 2/8/17.
 */
let helper      = require('../common/helper');
let md5         = require('md5');
let async       = require('async');
let knex        = require('../common/knex').knex;
let config      = require('../config');
let eventproxy  = require('eventproxy');
let smsService  = require('../services/SmsService');
let userService = require('../services/userService');
let _           = require('lodash');

let util = require('util');
let ep = new eventproxy();

const merchant = 'tb_merchant';
const sms_verify = 'tb_sms_verify';
const merchant_address = 'tb_merchant_address';

exports = module.exports = {
  login: function (req, res) {
    let phone = _.trim(req._params.phone);
    let password = _.trim(req._params.password);

    if (helper.has_empty(phone, password)) {
      return res.send(helper.apiMissRequiredParams());
    }

    knex(merchant).where('phone', phone).first().then(function (result) {
      if (result) {
        if (result.status == 0) {
          return res.send(helper.apiFail('账号被禁用, 请联系管理员'));
        }
        if (result.is_deleted == 1) {
          return res.send(helper.apiFail('账号已被删除, 请联系管理员'));
        }
        password = md5('shells' + password);
        if (helper.strcmp(password, result.password_md5) !== 0) {
          return res.send(helper.apiFail('密码错误'));
        }
        delete result.password_md5;
        req.session.user = result; //保存到session
        userService.setMerchantSessionKey(result.id, req.sessionID);
        return res.send(helper.apiSuccess('登录成功', result));
      } else {
        return res.send(helper.apiFail('该号码尚未注册'));
      }
    });
  },

  register: function (req, res) {
    let phone = req._params.phone;
    let password = req._params.password;
    let name = req._params.name;
    let address = req._params.address;

    if (helper.has_empty(phone, password, name, address) == true) {
      return res.json(helper.apiMissRequiredParams())
    }

    //查看用户是否已存在
    knex(merchant).where('phone', phone).first().then(function (result) {
      if (result) {
        return res.json(helper.apiFail('该手机号码已注册'));
      }
      let timestamp = helper.time();
      let data = {
        phone: phone,
        contact_phone: phone,
        password_md5: md5('shells' + password),
        name: name,
        address: address,
        create_time: timestamp,
        update_time: timestamp,
      };
      let merchant_address = {
        name: name,
        phone: phone,
        address: address,
        create_time: timestamp,
        update_time: timestamp,
      };

      let merchant_id;
      knex.transaction(function (trx) {
        knex.insert(data, 'id')
          .into(merchant)
          .transacting(trx)
          .then(function (id) {
            merchant_id = merchant_address['merchant_id'] = id;
            return knex.insert(merchant_address).into('tb_merchant_address').transacting(trx);
          })
          .then(trx.commit)
          .catch(trx.rollback)
      }).then(function (address_id) {
        if (merchant_id && address_id) {
          knex(merchant).where('phone', phone).first().then(function (result) {
            //保存商户到session
            userService.setMerchantSessionKey(result.id, req.sessionID);
            //删除验证码
            knex(sms_verify).where('phone', phone).del();
            delete result.password_md5;
            req.session.user = result; //保存到session
            return res.send(helper.apiSuccess('注册成功', result));
          });
        } else if (!merchant_id) {
          return res.send(helper.apiFail('新增商户失败'));
        } else if (!address_id) {
          return res.send(helper.apiFail('新增商户地址失败'));
        }
      }).catch(function (err) {
        return res.send(helper.apiFail('注册失败, 请重试'));
      });
    });
  },

  resetPassword: function (req, res) {
    let phone = _.trim(req._params.phone);
    let password = _.trim(req._params.password);
    let sms_verify_code = _.trim(req._params.sms_verify);

    if (helper.has_empty(phone, password, sms_verify_code)) {
      return res.send(helper.apiMissRequiredParams());
    }

    knex(sms_verify).where('phone', phone).first().then(function (result) {
      if (!result) {
        return res.send(helper.apiFail('尚未获取短信验证码'));
      } else {
        if (helper.strcmp(result.sms_verify_code, sms_verify_code) !== 0) {
          return res.send(helper.apiFail('短信验证码错误'));
        }
        if (helper.time() - result.create_time > 300) {
          return knex(sms_verify).where('phone', phone).del().then(function (affected_rows) {
            res.send(helper.apiFail('短信验证码过期，请重新获取'));
          });
        }
        knex(merchant).where('phone', phone).first().then(function (result) {
          if (!result) {
            return res.send(helper.apiFail('用户未注册'));
          } else {
            let new_password = md5('shells' + password);
            knex(merchant).where('phone', phone).update({password_md5: new_password}).then(function (affected_rows) {
              if (affected_rows === 1) {
                //删除验证码
                knex(sms_verify).where('phone', phone).delete().then(function (deleted_rows) {
                  return res.send(helper.apiSuccess('重设密码成功'));
                });
              } else {
                return res.send(helper.apiFail('重设密码失败'));
              }
            });
          }
        });
      }
    });
  },

  resetPasswordSms: function (req, res) {
    let phone = _.trim(req._params.phone);
    let token = _.trim(req._params.token);

    if (helper.has_empty(phone, token)) {
      return res.send(helper.apiMissRequiredParams());
    }

    if (!/^1[34578]\d{9}$/.test(phone)) {
      return res.json(helper.apiFail('请输入正确手机号码'));
    }
    if (helper.strcmp(md5('shells' + phone), token) !== 0) {
      return res.json(helper.apiFail('token错误'));
    }

    knex(merchant).where('phone', phone).first().then(function (result) {
      if (!result) {
        return res.send(helper.apiFail('该号码尚未注册'));
      } else if (result.is_deleted === 1) {
        return res.send(helper.apiFail('该账号已被删除, 请联系管理员'));
      } else {
        let sms_verify_code = Math.floor(100000 + Math.random() * 900000).toString();
        let msg = '【贝壳速配】，您的验证码是' + sms_verify_code;
        ep.all('sendResetSms', function (response) {
          return res.json(response);
        });
        sendSMS(phone, sms_verify_code, msg, 2);
      }
    });
  },

  addAddress: function (req, res) {
    let merchant = req.session.user;
    if (!merchant) {
      return res.send(helper.apiFail('未登录'));
    }
    let merchant_id = merchant.id;
    let phone = _.trim(req._params.phone);
    let name = _.trim(req._params.name);
    let address = _.trim(req._params.address);

    if (helper.has_empty(phone, name, address)) {
      return res.send(helper.apiMissRequiredParams());
    }

    let timestamp = helper.time();
    knex.insert({
      merchant_id: merchant_id,
      phone: phone,
      name: name,
      address: address,
      create_time: timestamp,
      update_time: timestamp
    }).into(merchant_address).then(function (merchant_address_id) {
      if (merchant_address_id) {
        knex(merchant_address).where('id', merchant_address_id).first().then(function (result) {
          return res.send(helper.apiSuccess('新增地址成功', result));
        });
      } else {
        return res.send(helper.apiFail('新增失败'));
      }
    });
  },

  updateAddress: function (req, res) {
    let merchant = req.session.user;
    if (!merchant) {
      return res.send(helper.apiFail('未登录'));
    }
    let merchant_id = merchant.id;
    let merchant_address_id = req._params.merchant_address_id;
    let phone = _.trim(req._params.phone);
    let name = _.trim(req._params.name);
    let address = req._params.address;

    if (helper.has_empty(merchant_address_id, phone, name, address)) {
      return res.send(helper.apiMissRequiredParams());
    }

    if (!validatePhone(phone)) {
      return res.send(helper.apiFail('请输入正确手机号码'));
    }

    knex(merchant_address).where('id', merchant_address_id).update({
      phone: phone,
      name: name,
      address: address,
      update_time: helper.time(),
    }).then(function (affected_rows) {
      if (affected_rows !== 1) {
        return res.send(helper.apiFail('更新失败'));
      } else {
        knex(merchant_address).where('id', merchant_address_id).first().then(function (result) {
          return res.send(helper.apiSuccess('修改地址成功', result));
        });
      }
    });
  },

  //删除收货地址
  //有订单关联的收货地址只是标记为已删除
  deleteAddress: function (req, res) {
    let merchant = req.session.user;
    if (!merchant) {
      return res.send(helper.apiFail('未登录'));
    }
    let merchant_id = merchant.id;
    let merchant_address_id = req._params.merchant_address_id;

    if (helper.has_empty(merchant_address_id)) {
      return res.send(helper.apiMissRequiredParams());
    }

    knex(merchant_address).where('id', merchant_address_id).first().then(function (result) {
      if (result) {
        knex('tb_order').where('merchant_address_id', merchant_address_id).first().then(function (has_relate) {
          if (has_relate) {
            knex(merchant_address).where({
              id: merchant_address_id,
              merchant_id: merchant_id,
            }).update({is_deleted: 1})
              .then(function (affected_rows) {
                if (affected_rows !== 1) {
                  return res.send(helper.apiFail('删除地址失败'));
                } else {
                  return res.send(helper.apiSuccess('删除地址成功'));
                }
              });
          } else {
            knex(merchant_address).where({
              id: merchant_address_id,
              merchant_id: merchant_id,
            }).delete().then(function (affected_rows) {
              if (affected_rows !== 1) {
                return res.send(helper.apiFail('删除地址失败'));
              } else {
                return res.send(helper.apiSuccess('删除地址成功'));
              }
            });
          }
        });
      } else {
        return res.send(helper.apiFail('收货地址不存在'));
      }
    });
  },

  addressList: function (req, res) {
    let merchant = req.session.user;
    if (!merchant) {
      return res.send(helper.apiFail('未登录'));
    }
    let merchant_id = merchant.id;
    let page = req._params.page;
    let server_time = req._params.server_time || helper.time();

    knex(merchant_address).where({
      merchant_id: merchant_id,
      is_deleted: 0,
    }).where('create_time', '<', server_time)
      .orderBy('create_time', 'desc')
      .orderBy('id', 'desc')
      .paginate(config.api_page_size, page)
      .then(function (data) {
        return res.send(helper.apiSuccess(data));
      });
  },

  userInfo: function (req, res) {
    let user = req.session.user;
    if (!user) {
      return res.send(helper.apiFail('未登录'));
    }
    knex(merchant).where('id', user.id).first().then(function (result) {
      delete result.password_md5;
      return res.send(helper.apiSuccess(result));
    });
  },

  updateUserInfo: function (req, res) {
    let user = req.session.user;
    if (!user) {
      return res.send(helper.apiFail('未登录'));
    }
    let name = _.trim(req._params.name);
    let phone = _.trim(req._params.phone);

    if (helper.has_empty(name, phone)) {
      return res.send(helper.apiMissRequiredParams());
    }
    knex(merchant).where('id', user.id).update({
      name: name,
      phone: phone
    }).then(function (affect_rows) {
      if (affect_rows === 1) {
        knex(merchant).where('id', user.id).first().then(function (result) {
          delete result.password_md5;
          return res.send(helper.apiSuccess('更新成功', result));
        });
      } else {
        return res.send(helper.apiFail('更新失败'));
      }
    })
  },

  registerSms: function (req, res) {
    let phone = req.query.phone;
    let token = req.query.token;
    if (helper.has_empty(phone, token) == true) {
      return res.json(helper.apiMissRequiredParams());
    }
    if (!/^1[34578]\d{9}$/.test(phone)) {
      return res.json(helper.apiFail('请输入正确手机号码'));
    }
    if (helper.strcmp(md5('shells' + phone), token) !== 0) {
      return res.json(helper.apiFail('token错误'));
    }

    knex(merchant).where({phone: phone}).first('id').then(function (data) {
      if (data) {
        return res.json(helper.apiFail('该号码已注册'));
      } else {
        let sms_verify_code = Math.floor(100000 + Math.random() * 900000).toString();
        //console.log(sms_verify_code);

        let msg = '感谢您注册贝壳速配，您的验证码是' + sms_verify_code;

        ep.all('sendRegisterSms', function (response) {
          return res.json(response);
        });
        sendSMS(phone, sms_verify_code, msg, 1);
      }
    });
  },

  verifyInfo: function (req, res) {

  },

  aboutShells: function (req, res) {
    knex('tb_about').first().then(function (result) {
      return res.send(helper.apiSuccess(result));
    })
  },
};

//发送验证码
//type 1 - 注册, 2 - 重设密码
let sendSMS =  function (phone, code, msg, type, res) {
  let event = type == 1 ? 'sendRegisterSms' : 'sendResetSms';
  let template_code, sign;
  if (type == 1) {
    template_code = config.sms.alidayu.ALIDAYU_REGISTER_TPL_ID;
    sign = config.sms.alidayu.ALIDAYU_SIGN;
  } else {
    template_code = config.sms.alidayu.ALIDAYU_RESET_TPL_ID;
    sign = config.sms.alidayu.ALIDAYU_RESET_SIGN;
  }

  if (helper.has_empty(phone, code, msg)) {
    return ep.emit(event, helper.apiMissRequiredParams());
  }

  //测试环境下将此值设为true，跳转发送短信步骤，将验证码设为1234
  let skipSms = false;
  if (skipSms) {
    code = '1234';
  }

  let data = {
    create_time: helper.time(),
    sms_verify_code: code,
  };
  knex(sms_verify).where('phone', phone).orderBy('create_time', 'desc').first().then(function (old) {
    if (old) {
      let diff = helper.time() - old.create_time;
      if (diff < 60) {
        return ep.emit(event, helper.apiFail('距离上次发送验证码时间过短，请1分钟后再发'));
      } else {
        knex(sms_verify).where('id', old.id).update(data).then(function (affected_rows) {
          ep.emit('insert', affected_rows);
        })
      }
    } else {
      data.phone = phone;
      knex(sms_verify).where('phone', phone).del();
      knex(sms_verify).insert(data).then(function (id) {
        ep.emit('insert', id);
      });
    }

    ep.all('insert', function (success) {
      //数据库插入或者更新数据后执行
      if (success === null) {
        return ep.emit(event, helper.apiFail('发送验证码失败，请重试'));
      } else {
        //todo 使用消息队列发送
        if (skipSms) {
          return ep.emit(event, helper.apiSuccess('验证码已发送，请注意查收'));
        } else {
          smsService.sendSms(phone, template_code, {code: code, product: '贝壳速配'}, sign)
            .then(function (send_resutl) {
              return smsService.verifyResult(send_resutl);
            })
            .then(function (send_result) {
              if (send_result) {
                return ep.emit(event, helper.apiSuccess('验证码已发送，请注意查收'));
              } else {
                knex(sms_verify).where('phone', phone).delete();
                return ep.emit(event, helper.apiFail('发送验证码失败，请重试'));
              }
            }).catch(function (error) {
              console.log(error);
              knex(sms_verify).where('phone', phone).delete();
              return ep.emit(event, helper.apiFail('发送验证码失败，请重试'));
          });
        }
      }
    });

  });
};

let validatePhone = function (phone) {
  return /^1[34578]\d{9}$/.test(phone);
};
